package com.agriculture.controller;

import com.agriculture.common.Response;
import com.agriculture.domain.User;
import com.agriculture.dto.auth.LoginDTO;
import com.agriculture.dto.auth.RegisterDTO;
import com.agriculture.dto.auth.ResetPasswordDTO;
import com.agriculture.dto.auth.VerifyIdentityDTO;
import com.agriculture.service.AuthService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@CrossOrigin
@RestController
@RequestMapping("/api/auth")
public class AuthController {
    private static final Logger log = LoggerFactory.getLogger(AuthController.class);
    @Autowired
    private AuthService authService;

    @PostMapping("/login")
    public ResponseEntity<?> login(@RequestBody LoginDTO loginDTO) {
        try {
            Response<?> response = authService.login(loginDTO);
            if (response.isSuccess()) {
                Map<String, Object> data = (Map<String, Object>) response.getData();
                return ResponseEntity.ok(Response.success("登录成功", data));
            }
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("登录失败", e);
            return ResponseEntity.ok(Response.error(e.getMessage()));
        }
    }

    @PostMapping("/logout")
    public ResponseEntity<?> logout() {
        return ResponseEntity.ok(Response.success("退出成功", null));
    }

    @PostMapping("/register")
    public ResponseEntity<?> register(@RequestBody RegisterDTO registerDTO) {
        try {
            Response<?> response = authService.register(registerDTO);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("注册失败", e);
            return ResponseEntity.ok(Response.error(e.getMessage()));
        }
    }

    @PostMapping("/reset-password")
    public ResponseEntity<?> resetPassword(@RequestBody ResetPasswordDTO resetDTO) {
        try {
            Response<?> response = authService.resetPassword(resetDTO);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("密码重置失败", e);
            return ResponseEntity.ok(Response.error(e.getMessage()));
        }
    }

    @PostMapping("/verify-identity")
    public ResponseEntity<?> verifyIdentity(@RequestBody VerifyIdentityDTO verifyDTO) {
        try {
            Response<?> response = authService.verifyIdentity(verifyDTO);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("身份验证失败", e);
            return ResponseEntity.ok(Response.error(e.getMessage()));
        }
    }
} 